package com.yafengliang.fileupload.controller;

import com.yafengliang.fileupload.util.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author liangyafeng
 * @Description:
 * @date 2020/4/20 16:21
 */
@Controller
@Slf4j
@RequestMapping(value = "server")
public class FileController {

    @RequestMapping(value = "toFile")
    public String toOpen(Model model){
        model.addAttribute("ip","localhost");
        model.addAttribute("port","8081");
        return "FileUpload";
    }

    @RequestMapping(value = "toImport")
    public ResponseEntity tpImpl(MultipartFile fileUpload, HttpServletRequest request)throws IOException{
        RestTemplate restTemplate = new RestTemplate();
        //获取临时文件
        String tempFilePath = System.getProperty("java.io.tmpdir")+fileUpload.getOriginalFilename();
        File file = new File(tempFilePath);
        fileUpload.transferTo(file);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Accept", MediaType.APPLICATION_JSON.toString());
        httpHeaders.setContentType(MediaType.parseMediaType("multipart/form-data;charset=UTF-8"));
        MultiValueMap<String,Object> param = new LinkedMultiValueMap<>();
        //把临时文件转换成FileSystemResource
        FileSystemResource resource = new FileSystemResource(tempFilePath);
        param.add("fileUpload",resource);
        HttpEntity<MultiValueMap<String,Object>> formEntity = new HttpEntity<>(param,httpHeaders);
        String imports = String.format("http://%s:%s/client/toImportFile", request.getParameter("ip"), request.getParameter("port"));
        ResponseEntity responseEntity = restTemplate.postForEntity(imports, formEntity, Result.class);
        log.info("tempFilePath={}",tempFilePath );
        return new ResponseEntity(responseEntity.getBody(), HttpStatus.OK);
    }
}
